import { updateUserUsingPost } from '@/services/backend/userController';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Modal } from 'antd';
import React from 'react';

interface Props {
  oldData?: API.User;
  visible: boolean;
  columns: ProColumns<API.User>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 更新节点
 *
 * @param fields
 */


/**
 * 更新弹窗
 * @param props
 * @constructor
 */


const UpdateModal: React.FC<Props> = (props) => {
  // 表单配置
  const formItemProps = {
    rules: [
      {
        required: true,
        message: '用户名不能为空！',
      },
      {
        min:2
      }
    ],
  };
  let { oldData, visible, columns, onSubmit, onCancel } = props;
  columns[1].formItemProps=formItemProps;
  let newArray =[...columns.slice(1, 2),...columns.slice(3, 5)]
  
  // 更新用户信息（管理员）
  const handleUpdate = async (fields: API.UserUpdateRequest) => {
    try {
      const res = await updateUserUsingPost(fields);
      oldData = res.data;
      message.success(res.message);
      return true;
    } 
    catch (error: any) {
      return false;
    }
  };

  if (!oldData) {
    return <></>;
  }
  return (
    <Modal
      destroyOnClose
      title={'更新'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <ProTable
        type="form"
        columns={newArray}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (values: API.UserUpdate) => {
          const res = await handleUpdate({
            ...values,
            id: oldData.id as any,
          });
          if (res) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};
export default UpdateModal;
